package com.cc.bsp.persistence.hibernate;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.Assert;

import com.cc.bsp.persistence.IQueryPageOrder;
import com.cc.bsp.persistence.entity.IEntity;
import com.cc.bsp.persistence.exception.PersistenceException;
import com.cc.bsp.persistence.util.BeansUtil;

public abstract class AbstractRootDaoSupport<T extends IEntity,ID extends Serializable> extends AbstractEntityXQLDao<T, ID> implements IHRootDao<T, ID> {

	public AbstractRootDaoSupport(Class<T> clazzz) {
		super(clazzz);
	
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findList(T entity) throws PersistenceException {
		
		Assert.notNull(entity);
		
		Criteria criteria = getSession().createCriteria(entity.getClass());
		
		Map<String,Object> map = BeansUtil.beans2MapForNullProperty(entity);
		
		Criterion criterion = Restrictions.allEq(map);
		
		criteria.add(criterion);
		
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> findList(T entity, IQueryPageOrder pageorder) throws PersistenceException {
		Assert.notNull(entity);
		
		Assert.notNull(pageorder);
		
		Criteria criteriaCount = getSession().createCriteria(entity.getClass());
		
		Map<String,Object> map = BeansUtil.beans2MapForNullProperty(entity);
		
		Criterion criterionCount = Restrictions.allEq(map);
		
		criteriaCount.add(criterionCount);
		
		long totalElements = getCount(criteriaCount);
		
		pageorder.createPage(totalElements);
		
		Criteria criteria = getSession().createCriteria(entity.getClass());
		
		Criterion criterion = Restrictions.allEq(map);
		
		criteria.add(criterion);
		
		criteria.setFirstResult(pageorder.getPage().getCurrentBeginRow());
		
		criteria.setMaxResults(pageorder.getPage().getCurrentEndRow());
		
		return criteria.list();

	}

	
}
